/*
在原版代码里,每一个组件都有自己的index和state数组

我们这里放在一起了

这么做有个问题, 如果某个组件中途卸载了,
重新渲染时候, 再取state就错位了

要想不错位 需要在react-dom/index.js里 组件卸载时 将对应的state也从hookStates里剔除
但... 怎么知道要卸载的组件的索引是个问题
*/

//这里存放着我们所有的状态
import PureComponent from './PureComponent';

const hookStates = [];
//hook的索引
export let hookIndex = 0;
export let scheduleUpdate;

export function useState(initialState){
  hookStates[hookIndex] = hookStates[hookIndex] || (typeof initialState === 'function' ? initialState()/*todo 应该只在组件挂载时渲染*/ : initialState);

  const currentIndex = hookIndex; //永远都是0

  //↓不像类 不会进行状态自动合并
  function setState(newState){
    if (typeof newState === 'function'){
      newState = newState(hookStates[currentIndex]);
    }

    hookStates[currentIndex] = newState;
    scheduleUpdate(); //当状态改变后要重新更新应用
  }

  return [hookStates[hookIndex++],setState];
}

export function useMemo(factory,deps){
  if(hookStates[hookIndex]){
    const [lastMemo, lastDeps] = hookStates[hookIndex];
    const same = deps.every((item, index) => item === lastDeps[index]);
    if (same) {
      hookIndex++;
      return lastMemo;
    }
  }

  const newMemo = factory()
  hookStates[hookIndex++] = [newMemo, deps];
  return newMemo;
}

export function useCallback(callback,deps){
  if (hookStates[hookIndex]) {
    const [lastCallback, lastDeps] = hookStates[hookIndex];
    const same = deps.every((item, index) => item === lastDeps[index]);
    if (same) {
      hookIndex++;
      return lastCallback;
    }
  }
  hookStates[hookIndex++] = [callback, deps];
  return callback;
}
